﻿using CommandLineParser.Arguments;
using CommandLineParser.Exceptions;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace Newbe.Nuget.LocalStore
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Newbe.Nuget.LocalStore";
            var options = new StartupOptions();
            var parser = new CommandLineParser.CommandLineParser();
            parser.ExtractArgumentAttributes(options);
            try
            {
                parser.ParseCommandLine(args);
                parser.ShowParsedArguments();
                var dir = options.Directory4Scaning;
                var localstore = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "localstore");
                while (true)
                {
                    if (!Directory.Exists(localstore))
                    {
                        Directory.CreateDirectory(localstore);
                    }
                    const string packagesConfig = "packages.config";
                    var files = dir.GetFiles(packagesConfig, SearchOption.AllDirectories);
                    var localpackageConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, packagesConfig);
                    Console.WriteLine($"{files.Length} {packagesConfig} found!");
                    var count = files.Length;
                    foreach (var file in files)
                    {
                        file.CopyTo(localpackageConfigFilename, true);
                        var process = Process.Start(new ProcessStartInfo("nuget.exe", "install -outputdirectory localstore")
                        {
                            WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
                            RedirectStandardError = true,
                            RedirectStandardOutput = true,
                            UseShellExecute = false
                        });
                        Debug.Assert(process != null, nameof(process) + " != null");
                        var re = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
                        process.WaitForExit();
                        Console.WriteLine($"all packages in {file.FullName} cached and {--count} left.");
                    }
                    var now = DateTime.Now;
                    Console.WriteLine($"caching job finished at {now}, next job will start at {now.AddSeconds(options.ScaningDurationSeconds)}");
                    Thread.Sleep(TimeSpan.FromSeconds(options.ScaningDurationSeconds));
                }
            }
            catch (CommandLineException e)
            {
                Console.WriteLine(e.Message);
                parser.ShowUsage();
            }
        }
    }

    public class StartupOptions
    {
        [DirectoryArgument('d', nameof(Directory4Scaning), Description = "whitch directory to be scaned",
            DirectoryMustExist = true, Optional = false)]
        public DirectoryInfo Directory4Scaning { get; set; }

        [ValueArgument(typeof(int), 's', "ScaningDurationSeconds", DefaultValue = 30 * 60, Description = "duration for scaning directory")]
        public int ScaningDurationSeconds { get; set; }
    }
}
